"""
Appium驱动管理类
负责初始化和管理移动设备驱动
"""

import time
from typing import Optional, Dict, Any
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverException

from .config_manager import config_manager


class DriverManager:
    """Appium驱动管理器"""
    
    def __init__(self, platform: str = "android"):
        """
        初始化驱动管理器
        
        Args:
            platform: 平台名称 (android/ios)
        """
        self.platform = platform.lower()
        self.driver: Optional[webdriver.Remote] = None
        self.device_config = config_manager.get_device_config(self.platform)
        self.test_config = config_manager.get_test_config()
        
    def start_driver(self) -> webdriver.Remote:
        """
        启动Appium驱动
        
        Returns:
            Appium驱动实例
        """
        try:
            server_url = config_manager.get_server_url()
            
            # 设置隐式等待时间
            desired_caps = self.device_config.copy()
            desired_caps['implicit_wait'] = self.test_config.get('implicit_wait', 10)
            
            print(f"正在连接Appium服务器: {server_url}")
            print(f"设备配置: {desired_caps}")
            
            self.driver = webdriver.Remote(server_url, desired_caps)
            
            # 设置隐式等待
            self.driver.implicitly_wait(self.test_config.get('implicit_wait', 10))
            
            print(f"成功启动 {self.platform} 驱动")
            return self.driver
            
        except Exception as e:
            print(f"启动驱动失败: {e}")
            raise
    
    def quit_driver(self) -> None:
        """关闭驱动"""
        if self.driver:
            try:
                self.driver.quit()
                print("驱动已关闭")
            except Exception as e:
                print(f"关闭驱动时出错: {e}")
            finally:
                self.driver = None
    
    def find_element(self, locator: str, value: str, timeout: int = None):
        """
        查找元素
        
        Args:
            locator: 定位方式
            value: 定位值
            timeout: 超时时间
            
        Returns:
            元素对象
        """
        if not self.driver:
            raise RuntimeError("驱动未初始化")
        
        timeout = timeout or self.test_config.get('explicit_wait', 20)
        
        try:
            element = WebDriverWait(self.driver, timeout).until(
                EC.presence_of_element_located((locator, value))
            )
            return element
        except TimeoutException:
            print(f"元素未找到: {locator}={value}")
            raise
    
    def find_elements(self, locator: str, value: str, timeout: int = None):
        """
        查找多个元素
        
        Args:
            locator: 定位方式
            value: 定位值
            timeout: 超时时间
            
        Returns:
            元素列表
        """
        if not self.driver:
            raise RuntimeError("驱动未初始化")
        
        timeout = timeout or self.test_config.get('explicit_wait', 20)
        
        try:
            elements = WebDriverWait(self.driver, timeout).until(
                EC.presence_of_all_elements_located((locator, value))
            )
            return elements
        except TimeoutException:
            print(f"元素未找到: {locator}={value}")
            return []
    
    def click_element(self, locator: str, value: str, timeout: int = None) -> bool:
        """
        点击元素
        
        Args:
            locator: 定位方式
            value: 定位值
            timeout: 超时时间
            
        Returns:
            是否成功点击
        """
        try:
            element = self.find_element(locator, value, timeout)
            element.click()
            return True
        except Exception as e:
            print(f"点击元素失败: {e}")
            return False
    
    def input_text(self, locator: str, value: str, text: str, timeout: int = None) -> bool:
        """
        输入文本
        
        Args:
            locator: 定位方式
            value: 定位值
            text: 要输入的文本
            timeout: 超时时间
            
        Returns:
            是否成功输入
        """
        try:
            element = self.find_element(locator, value, timeout)
            element.clear()
            element.send_keys(text)
            return True
        except Exception as e:
            print(f"输入文本失败: {e}")
            return False
    
    def get_element_text(self, locator: str, value: str, timeout: int = None) -> str:
        """
        获取元素文本
        
        Args:
            locator: 定位方式
            value: 定位值
            timeout: 超时时间
            
        Returns:
            元素文本
        """
        try:
            element = self.find_element(locator, value, timeout)
            return element.text
        except Exception as e:
            print(f"获取元素文本失败: {e}")
            return ""
    
    def is_element_present(self, locator: str, value: str, timeout: int = None) -> bool:
        """
        检查元素是否存在
        
        Args:
            locator: 定位方式
            value: 定位值
            timeout: 超时时间
            
        Returns:
            元素是否存在
        """
        try:
            self.find_element(locator, value, timeout)
            return True
        except TimeoutException:
            return False
    
    def take_screenshot(self, filename: str = None) -> str:
        """
        截图
        
        Args:
            filename: 文件名
            
        Returns:
            截图文件路径
        """
        if not self.driver:
            return ""
        
        if not filename:
            timestamp = int(time.time())
            filename = f"screenshot_{timestamp}.png"
        
        try:
            screenshot_path = f"reports/screenshots/{filename}"
            self.driver.save_screenshot(screenshot_path)
            print(f"截图已保存: {screenshot_path}")
            return screenshot_path
        except Exception as e:
            print(f"截图失败: {e}")
            return ""
    
    def swipe(self, start_x: int, start_y: int, end_x: int, end_y: int, duration: int = 1000):
        """
        滑动操作
        
        Args:
            start_x: 起始X坐标
            start_y: 起始Y坐标
            end_x: 结束X坐标
            end_y: 结束Y坐标
            duration: 持续时间(毫秒)
        """
        if not self.driver:
            raise RuntimeError("驱动未初始化")
        
        try:
            self.driver.swipe(start_x, start_y, end_x, end_y, duration)
        except Exception as e:
            print(f"滑动操作失败: {e}")
            raise
    
    def get_page_source(self) -> str:
        """
        获取页面源码
        
        Returns:
            页面源码
        """
        if not self.driver:
            return ""
        
        try:
            return self.driver.page_source
        except Exception as e:
            print(f"获取页面源码失败: {e}")
            return "" 